var Calendar = (function() {
    var fetchUpcoming = function() {
        $.ajax({
            type: 'GET',
            url: '/events/upcoming/2',
            dataType: 'json',
            success : function(events) {
                displayUpcoming(events);
            },
            error : function(xhr, type) {
                console.log("Error fetching upcoming events");
            }
        });
    };

    var displayUpcoming = function(events) {
        console.log("displaying events");
        var upcomingEventsElement = $('#upcomingEvents');
        $('.upcoming').removeClass('loading');


        $(events).each(function(idx) {
            var event = events[idx];
            upcomingEventsElement.append(createEventHtml(event));
        });


    };

    var createEventHtml = function(event) {
        //Container
        var li = $("<li></li>");

        //Title
        var title = $("<h2></h2>");
        title.text(event.summary);
        li.append(title);

        //Build event info
        var eventInfo = $('<ul></ul>').attr('class', 'event-info');

        var desc = event.description;
        //Description
        if (desc) {

            //Description text
            var description = $('<p></p>');
            description.html(desc); //used html to hide comment block containing meta data
            li.append(description);

            //Parse meta data
            var meta = {};
            if(desc.indexOf('<!--') > 0){
                var metaString = desc.substring(desc.indexOf('<!--')+4, desc.indexOf("-->")).trim();
                meta = (new Function("return " + metaString))();
            }

            //Presenters
            if(meta.presenters){
                var pres = $("<li></li>").attr('class', 'presenter');
                pres.text(meta.presenters.join(', '));
                eventInfo.append(pres);
            }
        }

        //Location
        if(event.location){
            var location = $("<li></li>").attr('class', 'location');
            location.text(event.location);
            eventInfo.append(location);
        }

        //Time
        //todo : time may be undefined for all day events
        var time = $("<li></li>").attr('class', 'calendar');
        var startTime = new Date(event.start.dateTime.value);
        var endTime = new Date(event.end.dateTime.value);
        time.html(startTime.format('dddd, mmmm dS, yyyy') + "<br/>" + startTime.format('h:MM tt') + " - " + endTime.format('h:MM tt Z'));


        var rsvp = $('<span></span>').attr('class', 'rsvp');
        var rsvpAnchor = $('<a></a>').attr('href', 'https://spreadsheets.google.com/viewform?formkey=dF9jU3RzY0N4ajJJemRycWJDTVl4Mnc6MQ&entry_5=' + event.summary);
        rsvpAnchor.text('RSVP');
        rsvp.append(rsvpAnchor);
        time.append(rsvp);

        eventInfo.append(time);
        li.append(eventInfo);

        return li;
    };

    return {
        fetch : fetchUpcoming
    }
})();